﻿using C1.Win.C1FlexGrid;
using C1.Win.C1Ribbon;
using CWCS.BLL;
using CWCS.BLL.NTIScModbus;
using CWCS.Common;
using CWCS.Common.Log;
using CWCS.Entity.SRM;
using CWCS.UIDesigner.SRMControl;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace CWCS.UI
{
    public partial class FrmSRMManager : C1RibbonForm
    {
        #region 自动关闭弹出框
        [DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

        public const int WM_CLOSE = 0x10;

        private void StartKiller()
        {
            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
            timer.Interval = 500;
            timer.Tick += new EventHandler(Timer_Tick);
            timer.Start();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            KillMessageBox();
            //停止Timer   
            ((System.Windows.Forms.Timer)sender).Stop();
        }

        private void KillMessageBox()
        {
            //依MessageBox的標題,找出MessageBox的視窗   
            IntPtr ptr = FindWindow(null, " ");
            if (ptr != IntPtr.Zero)
            {
                //找到則關閉MessageBox視窗   
                PostMessage(ptr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
            }
        }
        #endregion
        //private SRMBLL bll;
        //private delegate void RichBoxCallBack(RichTextBox rb, string msg);
        //private delegate void ShowSendLog_Delegate(string msg);
        //private delegate void ShowStatus_Delegate(SRM_Robot_Entity sc);
        //DataTable dtData = new DataTable();
        private string str;
        private delegate void RichBoxCallBack(RichTextBox rb, string msg);
        private delegate void RichPicCallBack();
        private Dictionary<string, string> AlarmInfoDic = new Dictionary<string, string>();
        string strPalletNu = string.Empty;
        private delegate void PictureCallBack(CRCObject cob, List<CRCStatus> cs);
        public Hashtable ht = Hashtable.Synchronized(new Hashtable());
        public Hashtable htcount = Hashtable.Synchronized(new Hashtable());
        ModbusBLLSRMRun bsb = new ModbusBLLSRMRun();
        private static int xx = 0;
        private static int cellSize = int.Parse(System.Configuration.ConfigurationManager.AppSettings["SCWidth"].ToString());
        private string zoneCode = System.Configuration.ConfigurationManager.AppSettings["ZoneCode"].ToString();
        private PictureBox pic1;
        public Dictionary<string, bool> dicEquipStatus = new Dictionary<string, bool>();
        private uint iLastErr = 0;
        private Int32 m_lUserID = -1;
        private bool m_bInitSDK = false;
        private bool m_bRecord = false;
        private Int32 m_lRealHandle = -1;
        int firecount = 0;
        private LogHelper log = new LogHelper("SC");
        private LogHelper scManualLog = new LogHelper("scManualLog");

        public FrmSRMManager()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.DoubleBuffer, true);
            this.SetStyle(ControlStyles.UserPaint, true);
            this.SetStyle(ControlStyles.ResizeRedraw, true);
        }
        private void FrmSRMManager_Load(object sender, EventArgs e)
        {
            try
            {
                bsb.ShowStatus += new ModbusBLLSRMRun.ShowEquipmentStatus(bsb_ENotifyCRCEventHandler);
                bsb.EDNotify += new  ModbusBLLSRMRun.DNotify(bsb_EDNotify);
                bsb.Start();
                InitAlarmInfo();
            }
            catch (Exception ex)
            {
            }
        }


        private void bsb_ENotifyCRCEventHandler(CRCObject cob, List<CRCStatus> cs)
        {
            try
            {
                DrawConnect(cob, cs);
            }
            catch { }
        }
        private void InitAlarmInfo()
        {
            if (File.Exists(".\\SRMAlarm_ROBO.txt"))
            {
                FileStream fs = new FileStream(".\\SRMAlarm_ROBO.txt", FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs);
                string strline = sr.ReadToEnd();
                string[] msg = strline.Split(new char[] { ';' });
                string[] msg2;
                for (int i = 0; i < msg.Length; i++)
                {
                    msg2 = msg[i].Split(new char[] { ',' });
                    if (msg2.Length > 1 && !AlarmInfoDic.ContainsKey(msg2[0]))
                        AlarmInfoDic.Add(msg2[0].Trim(), msg2[1].Trim());
                }
            }
        }

        public void WriteLog(string scno, string msg)
        {
            ShowText(rtb_msg, msg);
            log.Info(System.DateTime.Now.ToString("yyyyMMdd") + "业务逻辑-" + scno, msg);
        }
        private void bsb_EDNotify(string type, string msg)
        {
            if (type == "C")
                ShowText(rtb_conn, msg);
            else
                ShowText(rtb_msg, msg);
        }

        private void ShowText(RichTextBox rb, string msg)
        {
            if (rb.InvokeRequired)
            {
                RichBoxCallBack rbcb = new RichBoxCallBack(ShowText);
                this.Invoke(rbcb, new object[] { rb, msg });
            }
            else
            {
                if (rb.TextLength > 5000)
                    rb.Clear();
                if (msg.Contains("报警"))
                    rb.SelectionColor = Color.Red;
                rb.AppendText(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ": " + msg + "\r\n");
            }
        }
        [HandleProcessCorruptedStateExceptions]
        private void DrawConnect(CRCObject cco, List<CRCStatus> css)
        {
            try
            {
                if (cco == null) return;
                if (this.InvokeRequired)
                {
                    PictureCallBack pc = new PictureCallBack(DrawConnect);
                    this.Invoke(pc, new object[] { cco, css });
                }
                else
                {
                    CRCStatus findcs = css.Find(
                               delegate (CRCStatus info)
                               {
                                   return info.scno == cco.ScNo;
                               }
                           );
                    if (findcs != null)
                    {
                        if (!ht.Contains(cco.ScNo))
                        {
                            PictureBox p = new PictureBox();
                            p.MouseClick += pic_MouseClick;
                            p.Tag = cco.ScNo;
                            ht.Add(cco.ScNo, p);
                        }
                        PictureBox pic1 = (PictureBox)ht[cco.ScNo];
                        if (htcount.Contains(cco.ScNo))
                        {
                            if (htcount[cco.ScNo] == null || htcount[cco.ScNo].ToString() != findcs.NewLabelInfo)
                            {
                                htcount[cco.ScNo] = findcs.NewLabelInfo;
                                pic1.Refresh();
                                //pic1.Invalidate();
                            }
                        }
                        else
                        {
                            htcount.Add(cco.ScNo, string.IsNullOrEmpty(findcs.NewLabelInfo) ? "" : findcs.NewLabelInfo);
                            //pic1.Refresh();
                            pic1.Invalidate();
                        }
                        int num = int.Parse(cco.id) - 1;
                        int cell = cellSize + xx;
                        pic1.Name = "pic" + num;
                        pic1.Left = num * cell;
                        pic1.Top = 10;
                        pic1.Width = cell;
                        pic1.Height = 900;
                        pic1.Parent = this;
                        pic1.SizeMode = PictureBoxSizeMode.AutoSize;
                        Graphics g = pic1.CreateGraphics();


                        SolidBrush brush;
                        Pen pen = new Pen(new SolidBrush(Color.Black), 4);

                        Rectangle resOperation = new System.Drawing.Rectangle(15, 50, 35, 20);
                        ControlPaint.DrawButton(g, resOperation, ButtonState.Normal);

                        if (BLLBase.modeFlag.ContainsKey(findcs.scno))
                        {
                            findcs.taskMode = BLLBase.modeFlag[findcs.scno];
                        }
                        else
                            BLLBase.modeFlag.Add(findcs.scno, findcs.taskMode);

                        if (findcs.taskMode == SCTaskMode.Auto)
                        {
                            g.DrawString("自动", new Font(new FontFamily("宋体"), 10, FontStyle.Bold), new SolidBrush(Color.Blue), resOperation.X + 1, resOperation.Y + resOperation.Height / 2 - 7);
                        }
                        else
                        {
                            g.DrawString("手动", new Font(new FontFamily("宋体"), 10, FontStyle.Bold), new SolidBrush(Color.Red), resOperation.X + 1, resOperation.Y + resOperation.Height / 2 - 7);
                        }
                        //堆垛机载体
                        g.FillRectangle(new SolidBrush(cco.connectstatus == 1 ? Color.GreenYellow : cco.connectstatus == 2 ? Color.Green : Color.Red), 20, 238, 120, 12);

                        //堆垛机滚轮
                        g.DrawEllipse(new Pen(new SolidBrush(Color.Black), 1), 25, 243, 9, 9);
                        g.FillEllipse(new SolidBrush(Color.Black), 25, 243, 9, 9);
                        g.DrawEllipse(new Pen(new SolidBrush(Color.Black), 1), 125, 243, 9, 9);
                        g.FillEllipse(new SolidBrush(Color.Black), 125, 243, 9, 9);
                        //堆垛机主臂
                        g.FillRectangle(new SolidBrush(cco.connectstatus == 1 ? Color.GreenYellow : cco.connectstatus == 2 ? Color.Green : Color.Red), 70, 45, 16, 200);
                        //堆垛机电柜
                        g.FillRectangle(new SolidBrush(Color.SlateGray), 100, 177, 22, 60);
                        g.DrawString(cco.ScNo.Substring(cco.ScNo.Length - 2, 2), new Font("宋体", 12, FontStyle.Bold), new SolidBrush(Color.White), 98, 181);
                        //g.DrawString(cco.zoneCode, new Font("宋体", 12, FontStyle.Bold), new SolidBrush(Color.SkyBlue), 104, 216);
                        string QY = "";
                        if (cco.zonecode == "A")
                        {
                            QY = "浸润";
                        }
                        else if (cco.zonecode == "B")
                        {
                            QY = "化成";
                        }
                        else if (cco.zonecode == "C")
                        {
                            QY = "老化";
                        }
                        else if (cco.zonecode == "D")
                        {
                            QY = "分容";
                        }
                        else if (cco.zonecode == "E")
                        {
                            QY = "常温";
                        }
                        g.DrawString(QY, new Font("宋体", 12, FontStyle.Bold), new SolidBrush(Color.Black), 94, 150);
                        //堆垛机爬梯
                        for (int i = 45; i < 229; i = i + 17)
                        {
                            g.DrawRectangle(new Pen(brush = new SolidBrush(Color.SlateGray), 1), 87, i, 10, 18);
                        }
                        int lev = int.Parse(findcs.RackLevel);
                        lev = lev > 10 ? 10 : lev;
                        //爬梯与电柜的连接体
                        //g.DrawLine(pen = new Pen(brush = new SolidBrush(Color.Black), 4), 85 + num * cell, 301, 100 + num * cell, 201);
                        //堆垛机货叉
                        g.DrawRectangle(new Pen(new SolidBrush(Color.Black), 4), 22, (130 - 10 * lev) + 96, 41, 3);
                        g.DrawRectangle(new Pen(new SolidBrush(Color.Black), 4), 60, (130 - 10 * lev) + 76, 3, 20);
                        g.DrawRectangle(new Pen(new SolidBrush(Color.Black), 4), 60, (130 - 10 * lev) + 86, 20, 4);
                        //货物及任务号
                        if (findcs.forkStatus1 != 0 || findcs.forkStatus2 != 0)
                        {
                            pen.Width = 6;
                            pen.DashStyle = DashStyle.Solid;
                            pen.EndCap = LineCap.ArrowAnchor;
                            g.FillRectangle(new SolidBrush(int.Parse(findcs.FunctionReport) > 120 ? Color.Chocolate : Color.Gray), 20, (130 - 10 * lev) + 71, 38, 22);
                            if (int.Parse(findcs.FunctionReport) >= 114 && int.Parse(findcs.FunctionReport) <= 121) //取货箭头 
                                g.DrawLine(pen, 2, (130 - 10 * lev) + 71, 17, (130 - 10 * lev) + 71);
                            else if (int.Parse(findcs.FunctionReport) > 120)//放货箭头
                                g.DrawLine(pen, 17, (130 - 10 * lev) + 71, 2, (130 - 10 * lev) + 71);
                            if (findcs.forkStatus1 != 0 && findcs.forkStatus2 == 0)
                            {
                                g.DrawString("叉1", new Font("宋体", 10, FontStyle.Regular), new SolidBrush(Color.Black), 27, (130 - 10 * lev) + 75);
                            }
                            else if (findcs.forkStatus1 == 0 && findcs.forkStatus2 != 0)
                            {
                                g.DrawString("叉2", new Font("宋体", 10, FontStyle.Regular), new SolidBrush(Color.Black), 27, (130 - 10 * lev) + 75);
                            }
                            else if (findcs.forkStatus1 != 0 && findcs.forkStatus2 != 0)
                            {
                                g.DrawString("叉1&2", new Font("宋体", 10, FontStyle.Regular), new SolidBrush(Color.Black), 19, (130 - 10 * lev) + 75);
                            }
                        }
                        else
                            g.FillRectangle(new SolidBrush(Color.Transparent), 25, (130 - 25 * lev) + 71, 30, 22);
                        //状态信息及报警信息
                        if (findcs.NewLabelInfo != null)
                        {
                            string[] info = findcs.NewLabelInfo.Split(new char[] { '.' });
                            for (int i = 0; i <= info.Length - 1; i++)
                            {
                                if (cco.connectstatus == 0)
                                {
                                    g.DrawString(info[i], new Font("宋体", 10, FontStyle.Regular), new SolidBrush(Color.Red), 20, 259 + 20 * i);
                                }
                                else
                                {
                                    if (i < 10)
                                    {
                                        if (i == 4 && (info[i].Contains("手动") || info[i].Contains("无")))
                                            g.DrawString(info[i], new Font("宋体", 10, FontStyle.Regular), new SolidBrush(Color.Red), 20, 259 + 20 * i);
                                        else if (i == 0 && info[i].Contains("暂停"))
                                            g.DrawString(info[i], new Font("宋体", 10, FontStyle.Regular), new SolidBrush(Color.Red), 20, 259 + 20 * i);
                                        else if (i == 6 && (info[i].Contains("故障") || info[i].Contains("无")))
                                            g.DrawString(info[i], new Font("宋体", 10, FontStyle.Regular), new SolidBrush(Color.Red), 20, 259 + 20 * i);
                                        else
                                            g.DrawString(info[i], new Font("宋体", 10, FontStyle.Regular), new SolidBrush(Color.Blue), 20, 259 + 20 * i);
                                    }
                                }
                            }
                            if (findcs.AlarmMessage != "")
                            {
                                g.DrawString(findcs.AlarmMessage, new Font("宋体", 10, FontStyle.Regular), new SolidBrush(Color.Red), 20, 259 + 20 * 10);
                            }
                        }
                        this.Controls.Add(pic1);
                        //brush.Dispose();
                        pen.Dispose();
                        g.Dispose();
                    }
                }
            }
            catch (Exception E)
            {
            }
        }

        private void pic_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                //if (!BLLBase.loginFlag)
                //{
                //    FrmLogIn frmLogIn = new FrmLogIn();
                //    frmLogIn.ShowDialog();
                //}
                //if (!BLLBase.loginFlag)
                //{
                //    MessageBox.Show("用户校验失败,请重新校验!");
                //    return;
                //}
                BLLBase.loginTime = DateTime.Now;

                if (e.Button == MouseButtons.Right)
                {
                    PictureBox tag = (PictureBox)sender;
                    FrmSRMSend fs = null;
                    if (BLLBase.modeFlag[tag.Tag.ToString()] != SCTaskMode.Manual)
                    {
                        MessageBox.Show("请先将WCS模式改为手动,再使用手动操作功能！");
                        return;
                    }
                    fs = new FrmSRMSend(tag.Tag);
                    fs.ShowDialog();
                }
                else if (e.Button == MouseButtons.Left && e.Y >= 50 && e.Y <= 70 && e.X >= 15 && e.X <= 50)
                {
                    PictureBox tag = (PictureBox)sender;
                    if (BLLBase.modeFlag[tag.Tag.ToString()] == SCTaskMode.Auto)
                    {
                        BLLBase.modeFlag[tag.Tag.ToString()] = SCTaskMode.Manual;
                    }
                    else
                        BLLBase.modeFlag[tag.Tag.ToString()] = SCTaskMode.Auto;

                    scManualLog.Info("用户:" + BLLBase.user + "将WCS模式改为:" + (BLLBase.modeFlag[tag.Tag.ToString()] == SCTaskMode.Manual ? "手动" : "自动"));
                }
            }
            catch { }
        }
        private void getfire(string fireflag, string ADDRIP, string SCNO)
        {

            if (string.IsNullOrEmpty(ADDRIP))
            {
                return;
            }
            if (firecount == 0)
            {
                if (fireflag == "1")
                {

                    if (!DVR_INIT())
                    {
                        return;
                    }
                    if (!addrlogin(ADDRIP))
                    {
                        return;
                    }
                    Thread.Sleep(1000);
                    Preview();
                    //if (bll.WriteInfo(SRMCommand.CallBack, SCNO, new string[] { "0", "0", "0", "5" }, "", "", ""))
                    //    WriteLog(SCNO, SCNO + "WCS->SC 摄像头拍照成功，发送召回指令成功");
                    //else
                    //    WriteLog(SCNO, SCNO + "WCS->SC 摄像头拍照成功，发送召回指令失败：");
                    firecount = 1;

                }

            }
            else
            {
                RealData();
                //Thread.Sleep(1000);
                //cutpictrue();
                Thread.Sleep(1000);//
                cutjpegpictrue();
                Thread.Sleep(15000);
                StopRealData();
                //if (bll.WriteInfo(SRMCommand.CallBack, SCNO, new string[] { "0", "0", "0", "1" }, "", "", ""))
                //    WriteLog(SCNO, SCNO + "WCS->SC 摄像头拍照成功，发送召回指令成功");
                //else
                //    WriteLog(SCNO, SCNO + "WCS->SC 摄像头拍照成功，发送召回指令失败：");
            }
        }

        private bool addrlogin(string ADDRIP)
        {

            if (m_lUserID < 0)
            {
                string DVRIPAddress = ADDRIP; //设备IP地址或者域名
                Int16 DVRPortNumber = Int16.Parse("8000");//设备服务端口号
                string DVRUserName = "admin";//设备登录用户名
                string DVRPassword = "robo0000";//设备登录密码

                CHCNetSDK.NET_DVR_DEVICEINFO_V30 DeviceInfo = new CHCNetSDK.NET_DVR_DEVICEINFO_V30();
                //CHCNetSDK.NET_DVR_Init();

                m_lUserID = CHCNetSDK.NET_DVR_Login_V30(DVRIPAddress, DVRPortNumber, DVRUserName, DVRPassword, ref DeviceInfo);
                if (m_lUserID < 0)
                {
                    iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    str = "NET_DVR_Login_V30 failed, error code= " + iLastErr; //登录失败，输出错误号
                    MessageBox.Show(str);
                    return false;
                }
                else
                {
                    //登录成功
                    return true;
                }

            }
            else
            {
                //注销登录 Logout the device
                if (m_lRealHandle >= 0)
                {

                    return false;
                }

                if (!CHCNetSDK.NET_DVR_Logout(m_lUserID))
                {
                    iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    return false;
                }
                m_lUserID = -1;

            }
            return true;
        }

        private bool DVR_INIT()
        {
            m_bInitSDK = CHCNetSDK.NET_DVR_Init();
            if (m_bInitSDK == false)
            {
                return false;
            }
            else
            {
                //保存SDK日志 To save the SDK log
                CHCNetSDK.NET_DVR_SetLogToFile(3, "C:\\SdkLog\\", true);
                return true;
            }
        }

        private void Preview()
        {
            if (RealPlayWnd.InvokeRequired)
            {
                RichPicCallBack dlgtRichtxb = new RichPicCallBack(Preview);
                this.Invoke(dlgtRichtxb, new object[] { });
            }
            else
            {
                RealPlayWnd.Visible = true;
                if (m_lUserID < 0)
                {
                    // MessageBox.Show("Please login the device firstly");
                    // return false;
                }

                if (m_lRealHandle < 0)
                {
                    CHCNetSDK.NET_DVR_PREVIEWINFO lpPreviewInfo = new CHCNetSDK.NET_DVR_PREVIEWINFO();
                    lpPreviewInfo.hPlayWnd = RealPlayWnd.Handle;//预览窗口
                    lpPreviewInfo.lChannel = Int16.Parse("1");//预te览的设备通道
                    lpPreviewInfo.dwStreamType = 0;//码流类型：0-主码流，1-子码流，2-码流3，3-码流4，以此类推
                    lpPreviewInfo.dwLinkMode = 0;//连接方式：0- TCP方式，1- UDP方式，2- 多播方式，3- RTP方式，4-RTP/RTSP，5-RSTP/HTTP 
                    lpPreviewInfo.bBlocked = true; //0- 非阻塞取流，1- 阻塞取流
                    lpPreviewInfo.dwDisplayBufNum = 15; //播放库播放缓冲区最大缓冲帧数

                    // CHCNetSDK.REALDATACALLBACK RealData = new CHCNetSDK.REALDATACALLBACK(RealDataCallBack);//预览实时流回调函数
                    IntPtr pUser = new IntPtr();//用户数据

                    //打开预览 Start live view 
                    m_lRealHandle = CHCNetSDK.NET_DVR_RealPlay_V40(m_lUserID, ref lpPreviewInfo, null/*RealData*/, pUser);
                    Thread.Sleep(2000);
                    if (m_lRealHandle < 0)
                    {
                        iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                        str = "NET_DVR_RealPlay_V40 failed, error code= " + iLastErr; //预览失败，输出错误号
                        MessageBox.Show(str);
                        // return true;
                    }
                    else
                    {
                        //预览成功
                        // btnPreview.Text = "Stop Live View";
                        //return false;
                        RealData();
                        //Thread.Sleep(1000);
                        //cutpictrue();
                        Thread.Sleep(1000);
                        cutjpegpictrue();
                        Thread.Sleep(15000);
                        StopRealData();
                    }
                }
                else
                {
                    //停止预览 Stop live view 
                    if (!CHCNetSDK.NET_DVR_StopRealPlay(m_lRealHandle))
                    {
                        iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                        str = "NET_DVR_StopRealPlay failed, error code= " + iLastErr;
                        //MessageBox.Show(str);
                        //return true;
                    }
                    m_lRealHandle = -1;

                }
            }
            //return true;
        }


        private void RealData()
        {
            string sVideoFileName;
            String LogTitleHour = DateTime.Now.ToString("yyyyMMddHHmmss");
            sVideoFileName = "Record" + LogTitleHour + ".mp4";
            int lChannel = Int16.Parse("1"); //通道号 Channel number
            CHCNetSDK.NET_DVR_MakeKeyFrame(m_lUserID, lChannel);

            //开始录像 Start recording
            if (!CHCNetSDK.NET_DVR_SaveRealData(m_lRealHandle, sVideoFileName))
            {
                iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                str = "NET_DVR_SaveRealData failed, error code= " + iLastErr;
                return;
            }
            else
            {

            }
        }
        private void StopRealData()
        {
            if (!CHCNetSDK.NET_DVR_StopSaveRealData(m_lRealHandle))
            {
                iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                str = "NET_DVR_StopSaveRealData failed, error code= " + iLastErr;
                return;
            }
            else
            {
                str = "Successful to stop recording and the saved file is ";
                m_bRecord = false;
            }
        }
        private void cutpictrue()
        {
            string sBmpPicFileName;
            //图片保存路径和文件名 the path and file name to save
            sBmpPicFileName = "bakBMP_test12.bmp";

            //BMP抓图 Capture a BMP picture
            if (!CHCNetSDK.NET_DVR_CapturePicture(m_lRealHandle, sBmpPicFileName))
            {
                iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                str = "NET_DVR_CapturePicture failed, error code= " + iLastErr;
                //MessageBox.Show(str);
                // return;
            }
            else
            {
                str = "Successful to capture the BMP file and the saved file is " + sBmpPicFileName;
                //MessageBox.Show(str);
            }
            // return;
        }

        private void cutjpegpictrue()
        {
            string sJpegPicFileName;
            //图片保存路径和文件名 the path and file name to save
            String LogTitleHour = DateTime.Now.ToString("yyyyMMddHHmmss");
            sJpegPicFileName = "Fire_" + LogTitleHour + ".jpg";

            int lChannel = Int16.Parse("1"); //通道号 Channel number

            CHCNetSDK.NET_DVR_JPEGPARA lpJpegPara = new CHCNetSDK.NET_DVR_JPEGPARA();
            lpJpegPara.wPicQuality = 0; //图像质量 Image quality
            lpJpegPara.wPicSize = 2; //抓图分辨率 Picture size: 2- 4CIF，0xff- Auto(使用当前码流分辨率)，抓图分辨率需要设备支持，更多取值请参考SDK文档

            //JPEG抓图 Capture a JPEG picture
            if (!CHCNetSDK.NET_DVR_CaptureJPEGPicture(m_lUserID, lChannel, ref lpJpegPara, sJpegPicFileName))
            {
                iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                str = "NET_DVR_CaptureJPEGPicture failed, error code= " + iLastErr;
                // MessageBox.Show(str);
                return;
            }
            else
            {
                str = "Successful to capture the JPEG file and the saved file is " + sJpegPicFileName;
                //MessageBox.Show(str);
            }
            return;
        }
        public void RealDataCallBack(Int32 lRealHandle, UInt32 dwDataType, ref byte pBuffer, UInt32 dwBufSize, IntPtr pUser)
        {
        }
        private bool CUT_BMP()
        {
            string sBmpPicFileName;
            //图片保存路径和文件名 the path and file name to save
            sBmpPicFileName = "bakBMP_test.bmp";

            //BMP抓图 Capture a BMP picture
            if (!CHCNetSDK.NET_DVR_CapturePicture(m_lRealHandle, sBmpPicFileName))
            {
                iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                str = "NET_DVR_CapturePicture failed, error code= " + iLastErr;
                MessageBox.Show(str);
                return false;
            }
            else
            {
                str = "Successful to capture the BMP file and the saved file is " + sBmpPicFileName;
                // MessageBox.Show(str);
            }
            return true;
        }
        private void fd_Click(object sender, EventArgs e)
        {
            try
            {
                xx = xx + 2;
                for (int i = 0; i < ht.Count; i++)
                {
                    ((PictureBox)ht[i]).Image = null;
                    ((PictureBox)ht[i]).Refresh();
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void sx_Click(object sender, EventArgs e)
        {
            try
            {
                xx = xx - 2;
                for (int i = 0; i < ht.Count; i++)
                {
                    ((PictureBox)ht[i]).Image = null;
                    ((PictureBox)ht[i]).Refresh();
                }
            }
            catch (Exception ex)
            {

            }
        }

    }
}
